package com.dxysun.spring.mvc;

import com.dxysun.annotation.DXYRequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

public class DXYHandlerMapping
{
    private Object controller;
    private Method method;
    private Pattern pattern; //${} url占位符解析
    private Map<String, Integer> paramIndexMapping; //参数顺序

    public DXYHandlerMapping(Object controller, Method method, Pattern pattern)
    {
        this.controller = controller;
        this.method = method;
        this.pattern = pattern;
        paramIndexMapping = new HashMap<>();
        initParamIndexMapping(method);

    }

    public Object getController()
    {
        return controller;
    }

    public void setController(Object controller)
    {
        this.controller = controller;
    }

    public Method getMethod()
    {
        return method;
    }

    public void setMethod(Method method)
    {
        this.method = method;
    }

    public Pattern getPattern()
    {
        return pattern;
    }

    public void setPattern(Pattern pattern)
    {
        this.pattern = pattern;
    }

    public Map<String, Integer> getParamIndexMapping()
    {
        return paramIndexMapping;
    }

    public void setParamIndexMapping(Map<String, Integer> paramIndexMapping)
    {
        this.paramIndexMapping = paramIndexMapping;
    }

    private void initParamIndexMapping(Method method)
    {
        Annotation[][] annotations = method.getParameterAnnotations();
        for (int i = 0; i < annotations.length; i++)
        {
            for (Annotation annotation : annotations[i])
            {
                if (annotation instanceof DXYRequestParam)
                {
                    DXYRequestParam dxyRequestParam = (DXYRequestParam) annotation;
                    String name = dxyRequestParam.value();
                    if (!"".endsWith(name))
                    {
                        paramIndexMapping.put(name, i);
                    }
                }
            }
        }

        Class<?>[] clazzs = method.getParameterTypes();
        for (int i = 0; i < clazzs.length; i++)
        {
            if (clazzs[i] == HttpServletRequest.class || clazzs[i] == HttpServletResponse.class)
            {
                paramIndexMapping.put(clazzs[i].getSimpleName(), i);
            }
        }
    }
}
